package com.atguigu;

import java.util.function.Consumer;

public class DynamicArray<E> {

    private static final int INITIAL_CAPACITY=5 ;

    Object[] arr = null ;
    public DynamicArray(){
        arr = new Object[INITIAL_CAPACITY];
    }

    //数组中存储的元素的实际个数
    private int size ;

    public int size(){
        return size ;
    }

    public boolean isEmpty(){
        return size==0 ;
    }

    private void grow(){
        Object[] arr2 = new Object[size*2];
        for(int i = 0 ; i<size ; i++){
            arr2[i] = arr[i];
        }
        arr = arr2 ;
    }

    public void add(int index , E element){
        if(index<0 || index>size){
            throw new IndexOutOfBoundsException(index);
        }

        if(size==arr.length){
            grow();
        }

        for(int i = size-1;i>=index;i--){
            arr[i+1]=arr[i];
        }
        arr[index]=element ;
        size++;
    }

    public void add(E element){
        add(size,element);
    }

    public E get(int index){
        if(index<0 || index>=size){
            throw new IndexOutOfBoundsException(index);
        }

        return (E)arr[index] ;
    }

    public E remove(int index){
        if(index<0 || index>=size){
            throw new IndexOutOfBoundsException(index);
        }

        E oldValue = (E)arr[index];
        for(int i = index ; i<size-1 ; i++){
            arr[i] = arr[i+1];
        }
        arr[--size]=null;

        return oldValue ;
    }

    public E set(int index , E element){
        if(index<0 || index>=size){
            throw new IndexOutOfBoundsException(index);
        }
        E oldValue = (E)arr[index];
        arr[index] = element ;
        return oldValue ;
    }

    public void forEach(Consumer<E> consumer){
        for(int i = 0 ; i <size ; i++){
            consumer.accept((E)arr[i]);
        }
    }

    public String toString(){
        StringBuilder stringBuilder = new StringBuilder("[");
        for(int i = 0 ; i<size ; i++){
            stringBuilder.append(arr[i]).append( (i==size-1) ? "" : ",");
        }
        return stringBuilder.toString()+"]";
    }

}

/*


public class DynamicArray<E> {

    public int size(){
        return 0 ;
    }

    public boolean isEmpty(){
        return false ;
    }

    public void add(int index , E element){}

    public void add(E element){}

    public E get(int index){
        return null ;
    }

    public E remove(int index){
        return null ;
    }

    public E set(int index , E element){
        return null ;
    }

    public void forEach(Consumer<E> consumer){}

}




 */